package controllers

import (
	"chuanyou/db"
	"chuanyou/models"
	"encoding/json"
	"fmt"

	beego "github.com/beego/beego/v2/server/web"
)

type MainController struct {
	beego.Controller
}

type Classmastes struct {
	Name      string
	Sn        string
	Age       int
	Classname string
}

func (c *MainController) Get() {
	var student []*Classmastes
	db.DB.Raw("select name,sex,sn,classname from chuanyou.classmates limit 50").Scan(&student)

	c.Data["xueshengs"] = student

	c.Data["Website"] = "杜国燦.vip"
	c.Data["Email"] = "3301429920@qq.com"
	c.Data["Age"] = "20"
	c.Data["sex"] = "男"
	c.TplName = "index.tpl"
}

func (c *MainController) Zhuce() {

	c.TplName = "register.tpl"
}

func (c *MainController) Denglu() {

	c.TplName = "login.html"
}

func (c *MainController) Jiaoyou() {

	c.TplName = "jiaoyou.html"
}

func (c *MainController) Chongzhi() {

	c.TplName = "chongzhi.html"
}

func (c *MainController) Shanchu() {

	c.TplName = "shanhcu.html"
}

// 验证登录
func (c *MainController) YanZhengLogin() {
	//接受 参数sn
	sn := c.GetString("sn")
	//接受 参数pswd
	pswd := c.GetString("pswd")
	fmt.Println("收到了前端发过来的数据", sn, pswd)

	var currentPerson models.Classmates
	tx := db.DB.Raw("select * from chuanyou.classmates where sn=?", sn).Scan(&currentPerson)
	if tx.Error != nil {
		c.Data["json"] = "验证出错，错误是:" + tx.Error.Error()
		c.ServeJSON()
		return
	}

	if currentPerson.Pswd == pswd {
		c.Data["json"] = currentPerson
	} else {
		c.Data["json"] = nil
	}

	c.ServeJSON()
}

func (c *MainController) Doregister() {
	var user models.Classmates
	err := json.Unmarshal(c.Ctx.Input.RequestBody, &user)
	if err != nil {
		c.Data["json"] = "注册失败"
		c.ServeJSON()
		return
	}
	//存入数据库
	tx := db.DB.Create(user)
	if tx.Error != nil {
		c.Data["json"] = "注册失败，原因是：" + tx.Error.Error()
		c.ServeJSON()
		return
	}

	c.Data["json"] = "注册成功"
	c.ServeJSON()
}
